from applications import create_app
from flask_apscheduler import APScheduler
from datetime import datetime, timedelta
from applications.models import Device_borrow
from applications.extensions import db

app = create_app()
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()


# 创建检查借阅记录的函数
def check_borrow_status():
    seven_days_ago = datetime.now() - timedelta(days=7)

    # 查询未超时且借出日期超过7天的记录
    overdue_records = Device_borrow.query.filter(Device_borrow.status == 1,
                                                 Device_borrow.borrow_at <= seven_days_ago).all()

    # 更新超时记录的状态
    for record in overdue_records:
        record.status = 0

    db.session.commit()


# 定时任务，每天执行一次
@scheduler.task('cron', id='check_borrow_status', day_of_week='*', hour=0, minute=0)
def scheduled_job():
    check_borrow_status()


if __name__ == '__main__':
    app.run()
